import { resolve } from 'path'
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite'
import WindiCSS from 'vite-plugin-windicss'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import checker from 'vite-plugin-checker'
import DefineOptions from 'unplugin-vue-define-options/vite'
import { createStyleImportPlugin, AndDesignVueResolve } from 'vite-plugin-style-import'
import { createHtmlPlugin } from 'vite-plugin-html'
import vue from '@vitejs/plugin-vue'

import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'

const CWD = process.cwd()

// https://vitejs.dev/config/

export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  // 环境变量
  const { VITE_DROP_CONSOLE } = loadEnv(mode, CWD)

  // isBuild
  const isBuild = command === 'build'
  console.log(isBuild)

  return {
    plugins: [
      vue(),
      WindiCSS(),
      DefineOptions(),
      Components({
        // 自动按需引入组件
        resolvers: [AntDesignVueResolver()],
      }),
      vueJsx(), // 支持jsx
      createSvgIconsPlugin({
        // 支持svg
        // Specify the icon folder to be cached
        iconDirs: [resolve(CWD, 'src/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
      checker({
        // 加速检查
        typescript: true,
        // vueTsc: true,
        eslint: {
          lintCommand: 'eslint "./src/**/*.{.vue,ts,tsx}"', // for example, lint .ts & .tsx
        },
      }),
      createStyleImportPlugin({
        // 按需引入组件样式
        resolves: [AndDesignVueResolve()],
        libs: [
          {
            libraryName: 'ant-design-vue',
            esModule: true,
            resolveStyle: (name) => `ant-design-vue/es/${ name }/style/index`,
          },
        ],
      }),
      createHtmlPlugin({
        inject: {
          data: {
            title: 'index'
          },
        },
      })
    ],
    resolve: {
      alias: [
        {
          find: '@',
          replacement: resolve(__dirname, './src'),
        },
      ],
    },
    server: {
      host: '0.0.0.0',
      port: 8088,
      // proxy: {
      //   '/api': {
      //     target: 'https://nest-api.buqiyuan.site/api/',
      //     // target: 'http://localhost:7001',
      //     changeOrigin: true,
      //     rewrite: (path) => path.replace(/^\/api/, ''),
      //   }
      // },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {},
          javascriptEnabled: true,
          additionalData: '@import "ant-design-vue/lib/style/themes/default.less";@import \'src/styles/global.less\';',
        },
      },
    },
    esbuild: {
      pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
    },
  }
})
